import { execSync } from 'node:child_process';
import fs from 'node:fs';
import path from 'node:path';

// 当前项目根目录
const __dirname = process.cwd();

// code-workspace 文件路径
const workspacePath = path.resolve(__dirname, 'vben-admin.code-workspace');

// 读取 workspace 文件
let workspaceContent = fs.readFileSync(workspacePath, 'utf8');
// 处理 JSON 中的尾随逗号（trailing commas）
workspaceContent = workspaceContent
  .replaceAll(/(,\s*\})(\s*[}\]])/g, '$2')
  .replaceAll(/,\s*([\]}])/g, '$1');
const workspace = JSON.parse(workspaceContent);

// 过滤出 packages 下的目录
const targetPaths = workspace.folders
  .map((folder) => folder.path)
  .filter((p) => p.startsWith('packages/'));

console.log('🎯 检测到以下目标包路径:');
console.log(targetPaths.join('\n'));

// 遍历并执行 unpublish 流程
targetPaths.forEach((relativePath) => {
  const fullPath = path.resolve(__dirname, relativePath);
  const packageJsonPath = path.resolve(fullPath, 'package.json');

  // 检查是否存在 package.json
  if (!fs.existsSync(packageJsonPath)) {
    console.warn(`⚠️ 跳过 ${relativePath}：没有找到 package.json`);
    return;
  }

  console.log(`\n📦 正在处理: ${relativePath}`);

  try {
    // 读取 package.json 获取包名
    const pkgContent = fs.readFileSync(packageJsonPath, 'utf8');
    const pkg = JSON.parse(pkgContent);
    let packageName = pkg.name;

    if (!packageName) {
      console.warn(`⚠️ 跳过 ${relativePath}：package.json 中没有 name 字段`);
      return;
    }

    // 转换包名
    if (packageName.startsWith('@vben/')) {
      const suffix = packageName.split('/').pop();
      packageName = `mldong-vben-${suffix}`;
    } else if (packageName.startsWith('@vben-core/')) {
      const suffix = packageName.split('/').pop();
      packageName = `mldong-vben-core-${suffix}`;
    }

    // 执行 npm unpublish --force
    const cmd = `npm unpublish ${packageName} --force --registry=https://registry.npmjs.org/`;
    console.log(`⏳ 执行: ${cmd}`);
    execSync(cmd, { stdio: 'inherit', cwd: fullPath });

    console.log(`✅ 成功删除: ${packageName}`);
  } catch (error) {
    console.error(`❌ 删除失败: ${relativePath}`, error.message);
  }
});
